import { useNavigate } from 'react-router-dom';
import { useState } from "react";
import { RegisterService, codeValidateService, checkUsernameService } from '../api/UserApi';
import './Login.css';

function Register() {
  const navigate = useNavigate();

  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [passwordError, setPasswordError] = useState('');
  const [email, setEmail] = useState('');
  const [code, setCode] = useState('');
  const [codeError, setCodeError] = useState('');
  const [usernameError, setUsernameError] = useState('');

  const handleConfirmPasswordChange = (e) => {
    setConfirmPassword(e.target.value);
    if (e.target.value !== password) {
      setPasswordError('两次输入的密码不一致');
    } else {
      setPasswordError('');
    }
  }

  const handleUsernameChange = async (e) => { 
    setUsername(e.target.value);
    if (e.target.value.trim() === '') {
      setUsernameError('用户名不能为空');
      return;
    }
    try {
      const response = await checkUsernameService(e.target.value);
      if (response.status === 200) {
        setUsernameError('');
      } else {
        setUsernameError('用户名已存在');
      }
    } catch (err) {
      setUsernameError('用户名验证失败');
    }
  }

  const handleRegister = async () => {
    if (usernameError) {
      alert('请填写有效的用户名');
      return;
    }
    if (codeError) {
      alert('请填写有效的邀请码');
      //return;
    }
    const userData = {
      "username": username,
      "password": password,
      "confirmPassword": confirmPassword,
      "email": email,
      "invitationCode": code,
    }
    const response = await RegisterService(userData);
    if (response.status === 200) {
      alert('注册成功');
      navigate('/login');
    } else {
      alert('注册失败，请重试');
    }
  };

  return (
    <div className="login-container">
      <div className="login-box">
        <h2 className="logo-text">BT-7274</h2>
        <input
          type="text"
          placeholder="账号"
          value={username}
          onChange={handleUsernameChange}
        />
        <input
          type="password"
          placeholder="密码"
          value={password}
          onChange={e => {
            setPassword(e.target.value);
            if (e.target.value !== confirmPassword) {
              setPasswordError('两次输入的密码不一致');
            } else {
              setPasswordError('');
            }
          }}/>
        <input
          type="password"
          placeholder="确认密码"
          value={confirmPassword}
          onChange={handleConfirmPasswordChange}
        />
        <input
          type="email"
          placeholder="邮箱"
          value={email}
          onChange={e => setEmail(e.target.value)}
        />
        <input
          type="text"
          placeholder='邀请码'
          value={code}
          onChange={e => setCode(e.target.value)}
          onBlur={async () => {
            if (code.trim() === '') {
              setCodeError('邀请码不能为空');
              return;
            }
            try {
              const response = await codeValidateService(code);
              if (response.status === 200) {
                setCodeError('');
              } else {
                setCodeError('邀请码无效或已过期');
              }
            } catch (err) {
              setCodeError('邀请码验证失败');
            }
          }}
        />
        <button onClick={handleRegister}>注册</button>
        <div className="bottom-links">
          {/* 错误提示 */}
          {usernameError && (
            <div style={{ color: 'red', fontSize: 14, marginTop: 5 }}>
              {usernameError}
            </div>
          )}
          {passwordError && (
            <div style={{ color: 'red', fontSize: 14, marginTop: 5 }}>
              {passwordError}
            </div>
          )}
          {codeError && (
            <div style={{ color: 'red', fontSize: 14, marginTop: 5 }}>
              {codeError}
            </div>
          )}
          {usernameError && (
            <div style={{ color: 'red', fontSize: 14, marginTop: 5 }}>
              {codeError}
            </div>
          )}
          <span>已有账号？</span>
          <button
            className="register-link"
            onClick={() => navigate('/login')}
          >
            去登录
          </button>
        </div>
      </div>
    </div>
  );
}

export default Register;